const express = require('express')
const app = express()
const fs = require('fs')
const path = require('path') //解决路径
//公共配置
const configAll = require('./configuration.js')
/* ----------------- redis配置 ----------------- */
const redis = require('redis')
const redisClient = redis.createClient(configAll.redisConfig)
const { MongoClient } = require('mongodb')
const client = new MongoClient(configAll.mongodbConfig.url+'/book',configAll.mongodbConfig.options)
// require('./manage.js')
/* ----------------- socket配置 ----------------- */
const {
	createServer
} = require("http");
const httpServer = createServer(app)
const {
	Server
} = require("socket.io");
(async function() {
	//创建一个redis链接
	//链接redis，此方法为异步方法
	await redisClient.on('error', err => console.log('Redis Client Error', err));
	await redisClient.connect()
	await client.connect()
	const db = client.db('book')
	const io = new Server(httpServer, configAll.socketConfig)
	require('./tim')(redisClient, io, db)
	//全局中间件
	app.use(async (req, res, next) => {
		res.mongodb = db
		next()
	})
	
	//注册路由
	app.use(routers)
})()

const routers = require('./src/Routers/index.js') //路由模块
const cors = require('cors') //解决跨域
const joi = require('joi') //路由正则限制
//爬取
/* const cheerio = require('cheerio')
const superagent = require("superagent") */
const {
	expressjwt: analysisJwt
} = require('express-jwt') //解密token
const filter = (obj) => {
	return Object.fromEntries(
		Object.entries(obj)
		.filter(([key, value]) => value !== null && value !== undefined && Object.keys(value).length !== 0)
	);
}
// 192.168.1.156
app.use(express.static(path.join(__dirname, 'public')))
// 开放服务器 dist 目录,访问时会自动寻找index.html文件
app.use(express.static(path.join(__dirname, 'dist/build/h5')))
// app.use(express.static(path.join(__dirname, 'dist/pc')))
//解决跨域
app.use(cors())

app.use(express.json({
	limit: '2mb'
})) //解析json

//解析字符串,挂在req.auth
app.use(express.urlencoded({
	extended: true,
	limit: '2mb'
}))
//全局中间件
app.use(async (req, res, next) => {
	res.cc = function(msg, status = -1, data = null) {
		let info = {
			status,
			msg: msg instanceof Error ? msg.message : msg,
			data: data
		}
		res.send(info)
	}
	next()
})

//注册全局解析jwt/token
app.use(analysisJwt({
	secret: configAll.secreKey,
	algorithms: ['HS256']
}).unless({ //匹配不需要token接口
	path: [/^\/common\//, /getLivesList/, /getArticleListHot/, /^\/lives\//]
}))

//全局注册错误中间件
app.use((err, req, res, next) => {

	if (err instanceof joi.ValidationError) return res.cc(err, -1)
	//判断token
	if (err.name === 'UnauthorizedError') return res.cc('无效的token', 401)
	res.cc(err, -1)
	next()
})
//#region

//#endregion
httpServer.listen(80, () => {
	console.log('服务器运行')
})